/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.velocityme.session;

import com.velocityme.entity.FileAttachment;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import javax.ejb.EJBException;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author rcrida
 */
@Stateless
public class FileAttachmentBean implements FileAttachmentLocal {

    @PersistenceContext
    private EntityManager em;

    public FileAttachment findFileAttachment(KeyLocal key, String serverName) {
        key.validateKey();
        return (FileAttachment)em.createNamedQuery("findByServerName").setParameter("serverName", serverName).getSingleResult();
    }

    public BufferedInputStream getFileAttachmentInputStream(KeyLocal key, FileAttachment fileAttachment) {
        key.validateKey();
        try {
            InputStream fileInputStream = new FileInputStream(fileAttachment.getFile());
            if (fileAttachment.isCompressed() == true)
                fileInputStream = new GZIPInputStream(fileInputStream);
            return new BufferedInputStream(fileInputStream);
        } catch (IOException e) {
            throw new EJBException(e);
        }
    }

    public long getFileAttachmentLength(KeyLocal key, FileAttachment fileAttachment) {
        key.validateKey();
        if (fileAttachment.getLength() != -1L)
            return fileAttachment.getLength();
        // this is provided for backward compatability!
        File file = fileAttachment.getFile();
        return file.length();
    }
    
    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method" or "Web Service > Add Operation")
 
}
